package com.school.aftersalemanagement.callback;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.school.aftersalemanagement.entity.Result;
import com.school.aftersalemanagement.global.BaseActivity;
import com.school.aftersalemanagement.global.UserConfig;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by winkyle on 2017/11/1.
 */

public abstract class StringCallback extends Callback<String> {
    private String session;
    private boolean cycle;
    protected RequestCall requestCall;
    protected Gson gson = new Gson();
    protected Handler handler;
    protected int messageType;
    protected Context context;
    public StringCallback(RequestCall requestCall, Handler handler, int messageType, Context context, boolean cycle){
        this.requestCall = requestCall;
        this.handler = handler;
        this.messageType = messageType;
        this.context = context;
        this.cycle = cycle;
    }

    @Override
    public void onBefore(Request request, int id) {
        Log.d(requestCall.getClass().getSimpleName(),"网络请求之前");
    }

    @Override
    public void onAfter(int id) {
        Log.d(requestCall.getClass().getSimpleName(),"网络请求之后");
    }

    @Override
    public void inProgress(float progress, long total, int id) {
        Log.d(requestCall.getClass().getSimpleName(),"网络请求中：progress-"+progress+"、total-"+total+"、id-"+id);
    }

    @Override
    public String parseNetworkResponse(Response response, int id) throws IOException
    {
        Headers headers = response.headers();
        Log.d("info_headers", "header " + headers);
        List<String> cookies = headers.values("Set-Cookie");
        Log.d("info_cookies", "onResponse-size: " + cookies);
        if(cookies.size()>=1){
            String cookie = cookies.get(0);
            Log.d("info_cookies", "onResponse: " + cookie);
            session = cookie.substring(0, cookie.indexOf(";"));
            Log.d("info_s", "session is  :" + session);
            Log.d("cookieset",cookie);
            UserConfig.getInstance(context).setCookie(session);
        }
        return response.body().string();
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        Log.d(requestCall.getClass().getSimpleName()+"Error", e.toString());
        String errorType = null;
        if (UnknownHostException.class.equals(e.getClass())|| ConnectException.class.equals(e.getClass())) {
            if (cycle) {
                errorType = "请检查网络，无法建立连接";
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                       if(((BaseActivity)context).isWork())
                       requestCall.execute(StringCallback.this);
                    }
                }, 1500);
            }else {
                errorType = "请检查网络，操作失败";
            }
        } else if (SocketTimeoutException.class.equals(e.getClass())) {
            errorType = "网络连接超时，请保持网速良好";
        } else if (IOException.class.equals(e.getClass())) {
            errorType = "身份信息已失效，请重新登录";
        }
        showShort(errorType);
    }

    protected Result getResult(String response){
        Result result = gson.fromJson(response, Result.class);
        return result;
    }

    public void  showShort(String msg){
        ((BaseActivity)context).showShort(msg);
    }
}
